package cn.wit.summit.chwan.models.dbmanager;


import java.util.List;

import cn.wit.summit.chwan.models.db.HistorySearchTable;
import cn.wit.summit.chwan.models.greendao.gen.HistorySearchTableDao;
import cn.wit.summit.chwan.ui.base.MyApplication;

/**
 * Created by tangbl on 2017/12/2 0002.
 */

public class HistorySeachManager {

    private static HistorySeachManager historySeachManager;

    private HistorySeachManager(){
        mHistorySearchTableDao = MyApplication.getMyApplication().getmHistorySearchTableDao();
    }

    public static HistorySeachManager getInstance(){
        if(historySeachManager==null) historySeachManager = new HistorySeachManager();
        return historySeachManager;
    }

    private HistorySearchTableDao mHistorySearchTableDao;

    /**
     * 获取所有
     * */
    public List<HistorySearchTable> getAllSearch() {
        return mHistorySearchTableDao.queryBuilder().orderDesc(HistorySearchTableDao.Properties.Time).list();
    }

    /**
     * 插入
     * */
    public void insertSearch(String keyWord) {
        if (isExist(keyWord)) {
            HistorySearchTable temp = mHistorySearchTableDao.queryBuilder().where(HistorySearchTableDao.Properties.KeyWord.eq(keyWord)).unique();
            temp.setTime(System.currentTimeMillis());
            updataSearch(temp);
        } else {
            HistorySearchTable historySearchTable = new HistorySearchTable(null, keyWord
                    , System.currentTimeMillis());
            mHistorySearchTableDao.insertOrReplace(historySearchTable);
        }
    }

    /**
     * 更新
     * */
    public void updataSearch(HistorySearchTable historySearchTable) {
        if (historySearchTable == null) return;
        mHistorySearchTableDao.update(historySearchTable);
    }

    /**
     * 删除
     * */
    public void deleteSearch(String keyWord) {
        HistorySearchTable temp = mHistorySearchTableDao.queryBuilder().where(HistorySearchTableDao.Properties.KeyWord.eq(keyWord)).unique();
        if (temp!=null) {
            mHistorySearchTableDao.delete(temp);
        }
    }

    /**
     * 删除全部
     * */
    public void deleteSearchAll() {
        mHistorySearchTableDao.deleteAll();
    }

    /**
     * 是否存在
     * */
    public boolean isExist(String keyWord) {
        HistorySearchTable temp = mHistorySearchTableDao.queryBuilder().where(HistorySearchTableDao.Properties.KeyWord.eq(keyWord)).unique();
        if (temp==null)
            return false;
        else
            return true;
    }
}
